<template>
  <div>
    <el-upload
      :action="uploadAddress"
      class="uploader"
      accept="application/zip,application/gzip,application/x-tar"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :data="params"
      :on-progress="uploadProgress"
      :on-success="uploadSuccess"
      :on-error="uploadError"
    >
      <el-button size="small" type="primary">upload</el-button>
      <template v-if="!progressFlag">
        <span
          v-if="filePath"
          style="color:#67c23a;font-size:12px;"
        >have already uploaded</span>
        <span v-else style="color:#999;font-size:12px;">haven‘t uploaded</span>
      </template>
      <template v-if="progressFlag">
        <el-progress :percentage="progressPercent" />
      </template>
    </el-upload>
  </div>
</template>

<script>
import md5 from 'js-md5';
import { uploadToken } from '@/api/common';
export default {
  props: {
    fileUrl: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      uploadAddress: process.env.VUE_APP_UPLOAD_ADDRESS,
      filePath: '',
      fileName: '',
      fileSize: 50 * 1024 * 1024, // 5MB
      progressPercent: 0,
      progressFlag: false,
      params: {}
    };
  },
  mounted() {
    if (this.fileUrl) {
      this.filePath = this.fileUrl;
    }
  },
  methods: {
    async beforeUpload(file) {
      if (file.size > this.fileSize) {
        this.$message.warning('The size of the compressed package exceeds the 50MB limit');
        this.$refs.upload.abort();
        return false;
      }
      const res = await uploadToken();
      if (res.code !== 200) {
        this.$message.error('Network connection failure');
        return false;
      }
      this.params['token'] = res.data;
      this.params['key'] =
        md5(JSON.stringify(file)) + '.' + file.type.split('/')[1];
    },
    uploadSuccess(res) {
      this.filePath = res.key;
      this.loading = false;
      this.progressFlag = false;
      this.progressPercent = 0;
      this.$emit('succ', res.key);
    },
    uploadError(error) {
      const res = JSON.parse(JSON.stringify(error));
      this.progressFlag = false;
      this.progressPercent = 0;
      if (res.status === 401) {
        this.$message.error('Authentication and authorization failure');
      } else {
        this.$message.error('network connection error');
      }
    },
    uploadProgress(event, file, fileList) {
      this.progressFlag = true;
      this.progressPercent = parseInt((event.loaded / event.total) * 100);
    }
  }
};
</script>

<style lang="scss" scoped>
span {
  font-size: 14px;
  margin-left: 25px;
}
.el-progress {
  display: inline-block;
  width: 200px;
}
</style>
